package com.dream.inspect.modules.sys.common;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.dream.inspect.common.utils.R;
import com.dream.inspect.modules.app.constants.AttrConstants;
import com.dream.inspect.modules.dream.dao.SysDeptMapper;
import com.dream.inspect.modules.dream.dao.SysUserMapper;
import com.dream.inspect.modules.dream.pojo.SysDeptFormMap;
import com.dream.inspect.modules.dream.pojo.SysUserFormMap;
import com.dream.inspect.modules.sys.dao.AuditApplyDao;
import com.dream.inspect.modules.sys.dao.SysDeptDao;
import com.dream.inspect.modules.sys.dao.SysRoleDao;
import com.dream.inspect.modules.sys.dao.SysUserDao;
import com.dream.inspect.modules.sys.dao.SysUserRoleDao;
import com.dream.inspect.modules.sys.entity.AuditApplyEntity;
import com.dream.inspect.modules.sys.entity.SysDeptEntity;
import com.dream.inspect.modules.sys.entity.SysRoleEntity;
import com.dream.inspect.modules.sys.entity.SysUserEntity;
import com.dream.inspect.modules.sys.entity.SysUserRoleEntity;
import com.dream.inspect.modules.sys.shiro.ShiroUtils;

@Component
public class LoginCommon {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	@Autowired
	private AuditApplyDao auditApplyDao;
	@Autowired
	private SysDeptMapper sysDeptMapper;
	@Autowired
	private SysDeptDao sysDeptDao;

	public R login(String username, String password, String loginType) {
		try {
			// subject.getPrincipal();
			SysUserFormMap user = new SysUserFormMap();
			user.put("username", username);//token.getUsername());
			List<SysUserFormMap> ulist = sysUserMapper.findUserAndRole(user);
			if(null == ulist || ulist.size() == 0){
				return R.error("账号不存在!");
			}
			user = ulist.get(0);
			user.put("sessionId", SecurityUtils.getSubject().getSession().getId());
			user.remove("password");
			String deptName = "";// user.getStr("deptName");
			String realDeptName = "";
			R t = null;
			if (AttrConstants.PKI.equals(loginType)) {
				t = pkiResultDept(user.get("sfzh")+"");
 				//user.put("otherSysData", realDeptName);
			} else if (AttrConstants.PSTORE.equals(loginType)) {
				t = pstoreResultDept(user.get("sfzh")+"");
				//user.put("otherSysData", realDeptName);
			} else {
				return R.error("请选择登录方式:PKI/PSTORE");
			}
			/*if(t.get("code").equals("0")){
				// 获取外部民警信息成功
				realDeptName = t.get("data") + "";
			}*/
 			if (deptName.equals(realDeptName)) {
 				Subject subject = ShiroUtils.getSubject();
 				UsernamePasswordToken token = new UsernamePasswordToken(username, password);
				subject.login(token);
				if ((user.get("status") + "").equals("1")) {
					subject.getSession().setAttribute(AttrConstants.SESSION_USER, user);
					return R.ok().put(AttrConstants.DATA, user);
				} else {
					String roleName = user.getStr("roleName");
					return checkRoleType(roleName, user);
				}
			} else {
				Map<String, Object> resultMap = changeUserRoleAndStatusByDept(realDeptName, user);
				user.put("roleName", resultMap.get("roleName"));
				user.put("roleId", resultMap.get("roleId"));
				user.put("deptId", resultMap.get("deptId"));
				user.put("deptName", resultMap.get("realDeptName"));
				user.put("remark", resultMap.get("remark"));
				Subject subject = ShiroUtils.getSubject();
				UsernamePasswordToken token = new UsernamePasswordToken(username, password);
				subject.login(token);
				return checkRoleType(resultMap.get("roleName") + "", user);
			}
		} catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		} catch (IncorrectCredentialsException e) {
			return R.error("账号或密码不正确");
		} /*
			 * catch (LockedAccountException e) { return
			 * R.error("账号已被锁定,请联系管理员"); }
			 */catch (AuthenticationException e) {
			return R.error("账户验证失败");
		} catch (Exception e) {
			logger.error("login error : " + e);
			return R.error("账户验证失败");
		}
	}

	private R checkRoleType(String roleName, SysUserFormMap user) {
		R r = new R();
		boolean flag = checkRole(roleName);
//		Map<String, Object> resultMap = new HashMap<String, Object>();
//		resultMap.put("user", user);
		if (flag) {
			r.put("code", "1");
			r.put("msg", "未激活，请选择申请激活roleA或roleB激活");
		} else {
			r.put("code", "2");
			r.put("msg", "未激活,请申请激活");
		}
		r.put(AttrConstants.DATA, user);
		return r;
	}

	private boolean checkRole(String roleKey) {
		boolean flag = false;
		switch (roleKey) {
		case "role2":
			flag = true;
			break;
		case "role2A":
			flag = true;
			break;
		case "role2B":
			flag = true;
			break;
		case "role3":
			flag = true;
			break;
		case "role3A":
			flag = true;
			break;
		case "role3B":
			flag = true;
			break;
		case "role4":
			flag = true;
			break;
		case "role4A":
			flag = true;
			break;
		case "role4B":
			flag = true;
			break;
		default:
			flag = false;
			break;
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)
	public R applyActivation(Map<String, Object> params) {
		AuditApplyEntity apply = new AuditApplyEntity();
		List<AuditApplyEntity> list = auditApplyDao.selectList(new EntityWrapper<AuditApplyEntity>().eq("audit_flag", "0").eq("user_id", params.get("userId")));
		apply.setRoleId(Long.parseLong(params.get("roleId")+""));
		apply.setUserId(Long.parseLong(params.get("userId")+""));
		if(null != params.get("userInfo")){
			apply.setUserInfo(params.get("userInfo")+"");
		}
		apply.setCreateTime(new Date());
		if(null != list && list.size() > 0){
			apply.setId(list.get(0).getId());
			auditApplyDao.updateById(apply);
		}else{
			auditApplyDao.insert(apply);
		}
		//更新用户激活状态为激活中
		SysUserEntity user = new SysUserEntity();
		user.setUserId(Long.parseLong(params.get("userId")+""));
		user.setStatus(2);//激活中
		sysUserDao.updateById(user);
		return R.ok().put("data","请等待总队或管理员审批");
	}

	public R getRoleInfo(Map<String, Object> params) {
		String roleId = params.get("roleId") + "";
		String roleName = params.get("roleName") + "";
		Wrapper<SysRoleEntity> wrapper = new EntityWrapper<SysRoleEntity>()
				.ne("ROLE_ID", roleId)
				.like("ROLE_NAME",roleName);
		return R.ok().put("page", sysRoleDao.selectList(wrapper));
	}
	
	@Transactional(rollbackFor = Exception.class)
	private Map<String, Object> changeUserRoleAndStatusByDept(String deptName, SysUserFormMap user) throws Exception{
		Map<String, Object> result = new HashMap<String, Object>();
		// 根据部门修改角色
		/*SysDeptFormMap sdMap = new SysDeptFormMap();
		sdMap.put("deptName", deptName);
		sdMap.put("delFlag", "0");*/
		//List<SysDeptFormMap> list = sysDeptMapper.findDeptRole(sysDeptFormMap);
		List<SysDeptEntity> list = sysDeptDao.selectList(new EntityWrapper<SysDeptEntity>().eq("full_name", deptName).eq("del_flag", "0"));
		if(list == null || list.size()==0){
			throw new Exception("未查询到部门");
		}
		SysDeptEntity sdEntity = new SysDeptEntity();
		sdEntity = list.get(0);
		// 获取该部门的角色ID
		String sdlevelRole = getSdLevelRole(sdEntity.getLevel());
		SysRoleEntity srEntity = new SysRoleEntity();
		List<SysRoleEntity> srlist = sysRoleDao.selectList(new EntityWrapper<SysRoleEntity>().eq("role_name", sdlevelRole));
		if(null == srlist || srlist.size() == 0){
			throw new Exception("未查询到该部门所属角色");
		}
		srEntity = srlist.get(0);
		sysUserRoleDao.delete(new EntityWrapper<SysUserRoleEntity>().eq("user_Id", user.get("userId")));
		SysUserRoleEntity entity = new SysUserRoleEntity();
		entity.setRoleId(srEntity.getRoleId());
		entity.setUserId(Long.parseLong(user.get("userId") + ""));
		sysUserRoleDao.insert(entity);
		// 更新用户status
		SysUserEntity editUser = new SysUserEntity();
		editUser.setUserId(Long.parseLong(user.get("userId") + ""));
		editUser.setStatus(0);
		editUser.setDeptId(sdEntity.getDeptId());
		sysUserDao.updateById(editUser);
		result.put("roleId", srEntity.getRoleId());
		result.put("roleName", srEntity.getRoleName());
		result.put("deptId", sdEntity.getDeptId());
		result.put("realDeptName", deptName);
		result.put("remark", srEntity.getRemark());
		return result;
	}
	
	// 调用警综数据
	private R pkiResultDept(String sfzh){
		/*User u = new User();
        String inxml = sfzh;
        Map<String, Object>  map  = u.dqRyxx(inxml);
        if(map != null)
        {
            String type = MyHelp.OtoS(map.get("TYPE")); //返回结果类型
            String description = MyHelp.OtoS(map.get("DESCRIPTION")); //返回结果描述
            Object returnmsg = map.get("RETURNMSG");
            System.out.println("返回结果类型：" + type + "；返回结果描述：" + description + "；返回详细信息：" + returnmsg);
            //正常返回数据
            if(StringUtils.equals(type, "10000"))
            {
                //存在数据
                Map<String, Object> sjmap = (Map<String, Object>) returnmsg;
                System.out.println("返回数据量：" + sjmap);
            }else{
            logger.error("获取失败: 失败code为:" + type + " 描述:" + description);
            R.error("获取pki数据失败");
            }
        }*/
		return R.ok();
	}
	
	private R pstoreResultDept(String sfzh){
		return R.ok();
	}
	
	private String getSdLevelRole(String level){
		String role = "";
		switch (level) {
		case "1":
			role = "role1";
			break;
		case "2":
			role = "role2";
			break;
		case "3":
			role = "role3";
			break;
		case "4":
			role = "role4";
			break;
		}
		return role;
	}
}
